package com.seed.web;

import com.plugin.seed.web.bind.annotation.LoginUser;
import com.plugin.seed.web.support.AbstractLoginUserMethodArgumentResolver;
import com.seed.User;
import com.seed.UserRoleRelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.NativeWebRequest;

/**
 * @author Peter Fan
 */
@Component
public class DemoLoginUserMethodArgumentResolver extends AbstractLoginUserMethodArgumentResolver {

    @Autowired
    private UserRoleRelService userRoleRelService;

    /**
     * 示例：从request header中获取指定值，然后封装当前登录用户
     */
    @Override
    protected Object doResolve(LoginUser loginUser, MethodParameter parameter, NativeWebRequest request) {
        String[] headerValues = request.getHeaderValues(loginUser.name());
        if (headerValues == null || headerValues[0] == null || headerValues[0].isEmpty()) {
            return new User();
        }
        User user = new User();
        user.setId(Integer.parseInt(headerValues[0]));
        user.setRoleList(userRoleRelService.queryUserRole(user.getId()));
        return user;
    }
}
